//
//  VideoPostTool.m
//  ScheduleMeetingApp
//
//  Created by 七夜 on 17/1/19.
//  Copyright © 2017年 七夜. All rights reserved.
//

#import "ImagePostTool.h"
#define NOTIFY_AND_LEAVE(X) {[self cleanup:X]; return;}
#define DATA(X) [X dataUsingEncoding:NSUTF8StringEncoding]

// Posting constants
// Posting constants
#define IMAGE_CONTENT @"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.png\"\r\nContent-Type: image/png\r\n\r\n"
#define VEDIO_CONTENT @"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.mov\"\r\nContent-Type: video/mov\r\n\r\n"
#define STRING_CONTENT @"Content-Disposition: form-data; name=\"%@\"\r\n\r\n"
#define MULTIPART @"multipart/form-data; boundary=------------0x0x0x0x0x0x0x0x"
@implementation ImagePostTool
- (NSData*)generateFormDataFromPostDictionary:(NSArray*)dict
{
    id boundary = @"------------0x0x0x0x0x0x0x0x";
    
    NSMutableData* result = [NSMutableData data];
    for (int i = 0; i < [dict count]; i++)
    {
        NSArray* keys = [dict[i] allKeys];
        
        id value = [dict[i] valueForKey: [keys objectAtIndex:0]];
        [result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        if ([value isKindOfClass:[NSData class]])
        {
            NSString *time = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
            // handle image data
            NSString *formstring = [NSString stringWithFormat:IMAGE_CONTENT, [keys objectAtIndex:0],time];
            [result appendData: DATA(formstring)];
            [result appendData:value];
        }
        else
        {
            // all non-image fields assumed to be strings
            NSString *formstring = [NSString stringWithFormat:STRING_CONTENT, [keys objectAtIndex:i]];
            [result appendData: DATA(formstring)];
            [result appendData:DATA(value)];
        }
        
        NSString *formstring = @"\r\n";
        [result appendData:DATA(formstring)];
    }
    
    NSString *formstring =[NSString stringWithFormat:@"--%@--\r\n", boundary];
    [result appendData:DATA(formstring)];
    return result;
}
- (id )UpLoadingForInfo:(NSArray *)post_dict
{
    NSData *postData = [self generateFormDataFromPostDictionary:post_dict];
    
    
    NSURL *url = [NSURL URLWithString:NETworkUpdateURL];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    
    [urlRequest setHTTPMethod: @"POST"];
    [urlRequest setValue:MULTIPART forHTTPHeaderField: @"Content-Type"];
    [urlRequest setHTTPBody:postData];
    [urlRequest setTimeoutInterval:30];
    NSError *error;
    NSURLResponse *response;
    NSLog(@"Contacting TwitPic....");
    
    NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
    if (!error) {
         NSDictionary * info = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
         return info;
    }else{
        if (error.code == -1009) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新，
                [AxcUI_Toast AxcUI_showCenterWithText:@"网络已断开"];
            });
        }else if (error.code == -1005){
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新，
                [AxcUI_Toast AxcUI_showCenterWithText:@"网络连接已中断"];
            });
        }else if(error.code == -1001){
            dispatch_async(dispatch_get_main_queue(), ^{
                [AxcUI_Toast AxcUI_showCenterWithText:@"请求超时"];
            });
        }else if (error.code == -1003){
            dispatch_async(dispatch_get_main_queue(), ^{
                [AxcUI_Toast AxcUI_showCenterWithText:@"未能找到使用指定主机名的服务器"];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
               [AxcUI_Toast AxcUI_showCenterWithText:[NSString stringWithFormat:@"code:%ld %@",error.code,error.localizedDescription]];
            });
        }
        return error;
    }
}

- (NSData*)generateVedioFormDataFromPostDictionary:(NSArray*)dict
{
    id boundary = @"------------0x0x0x0x0x0x0x0x";
    
    NSMutableData* result = [NSMutableData data];
    for (int i = 0; i < [dict count]; i++)
    {
        NSArray* keys = [dict[i] allKeys];
        
        id value = [dict[i] valueForKey: [keys objectAtIndex:0]];
        [result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        if ([value isKindOfClass:[NSData class]])
        {
            NSString *time = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
            // handle image data
            NSString *formstring = [NSString stringWithFormat:VEDIO_CONTENT, [keys objectAtIndex:0],time];
            [result appendData: DATA(formstring)];
            [result appendData:value];
        }
        else
        {
            // all non-image fields assumed to be strings
            NSString *formstring = [NSString stringWithFormat:STRING_CONTENT, [keys objectAtIndex:i]];
            [result appendData: DATA(formstring)];
            [result appendData:DATA(value)];
        }
        
        NSString *formstring = @"\r\n";
        [result appendData:DATA(formstring)];
    }
    
    NSString *formstring =[NSString stringWithFormat:@"--%@--\r\n", boundary];
    [result appendData:DATA(formstring)];
    return result;
}
- (id )UpLoadingVedioForInfo:(NSArray *)post_dict
{
    NSData *postData = [self generateVedioFormDataFromPostDictionary:post_dict];
    
    
    NSURL *url = [NSURL URLWithString:NETworkUpdateURL];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    
    [urlRequest setHTTPMethod: @"POST"];
    [urlRequest setValue:MULTIPART forHTTPHeaderField: @"Content-Type"];
    [urlRequest setHTTPBody:postData];
    [urlRequest setTimeoutInterval:30];
    NSError *error;
    NSURLResponse *response;
    NSLog(@"Contacting TwitPic....");
    
    NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
    if (!error) {
        NSDictionary * info = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
        return info;
    }else{
        if (error.code == -1009) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新，
                [AxcUI_Toast AxcUI_showCenterWithText:@"网络已断开"];
            });
        }else if (error.code == -1005){
            dispatch_async(dispatch_get_main_queue(), ^{
                //回调或者说是通知主线程刷新，
                [AxcUI_Toast AxcUI_showCenterWithText:@"网络连接已中断"];
            });
        }else if(error.code == -1001){
            dispatch_async(dispatch_get_main_queue(), ^{
                [AxcUI_Toast AxcUI_showCenterWithText:@"请求超时"];
            });
        }else if (error.code == -1003){
            dispatch_async(dispatch_get_main_queue(), ^{
                [AxcUI_Toast AxcUI_showCenterWithText:@"未能找到使用指定主机名的服务器"];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [AxcUI_Toast AxcUI_showCenterWithText:[NSString stringWithFormat:@"code:%ld %@",error.code,error.localizedDescription]];
            });
        }
        return error;
    }
}


@end
